<?php

namespace App\Modules\Finance\Models;

use App\Modules\Finance\Services\CashAccountService;
use Illuminate\Database\Eloquent\Model;
use DB;

/**
 * Class Bill 账单
 * @package App\Modules\Finance\Models
 */
class FinancialPayMerchantBalance extends Model
{
	protected $table = 'financial_pay_merchant_balance';
	//recharge_amount:充值金额
    protected $fillable = ['distribution_channel_id','pay_merchant_company_id', 'accumulative_withdrawal_amount','enable_withdrawal_amount', 'latest_withdrawal_amount', 'latest_withdraw_time','withdraw_pending_amount','commission_rate'];

    static function getChannelEnableWithdraw($channel_id,$is_company){

        $obj = self::orderBy('enable_withdrawal_amount','desc')->where('distribution_channel_id',$channel_id);
        if($is_company == 0){
            //TODO 将1替换成掌维公司id
            $obj->whereNotIn('pay_merchant_company_id',explode(',',env('ZW_COMPANY_ID')));
        }
        $res = $obj->first();

        return $res;
    }

    static function getFinancialStatSingle($channelId,$pay_merchant_company_id) {
        return self::where('distribution_channel_id',$channelId)->where('pay_merchant_company_id',$pay_merchant_company_id)->first();
    }

    static function updateBalanceByWithdraw($money,$channelId,$pay_merchant_company_id){
        $financialStat = self::getFinancialStatSingle($channelId,$pay_merchant_company_id);
        if(!empty($financialStat)) {
            $enable_amount = $financialStat['enable_withdrawal_amount'] - $money;
            $withdraw_pending_amount = $financialStat['withdraw_pending_amount'] + $money;

            //修改可提现总额
            $financialStat['enable_withdrawal_amount'] = $enable_amount;
            //修改提现中金额
            $financialStat['withdraw_pending_amount'] = $withdraw_pending_amount;
            //修改最近提现金额
            $dataFinancialStat['latest_withdrawal_amount'] = $money;
            //修改提现时间
            $financialStat['latest_withdraw_time'] = date('Y-m-d H:i:s');

            $financialStat->save();
        }
    }

    static function getChannelEnableWithdrawByCompanyId($channel_id,$orderBy='desc') {
        $obj = self::orderBy('pay_merchant_company_id',$orderBy)
            ->where('distribution_channel_id',$channel_id);
        return $obj->get();
    }
}
 